<?php


namespace app\yperp\logic;

use app\yperp\model\Supplier;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client as GuzzleHttpClient;
use think\Db as ThinkDb;
use app\yperp\model\Brand as BrandModel;
use Fastposter\Client;
use app\admin\model\Attachment as AttachmentModel;
use think\Db;
use think\Image;
use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\yperp\model\GoodsSkuStandby;

class Brand
{
    private static $instance;
    protected  $token;
    public static function getInstance()
    {
        if (!defined('PUBLIC_PATH')) {
            define('PUBLIC_PATH', '/');
        }
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    function error($massage = '')
    {
        return ['status' => 0, 'massage' => $massage];
    }

    function success($massage = '')
    {
        return ['status' => 1, 'massage' => $massage];
    }
    public function conflates($goods_id = null)
    {
        $goods = GoodsSkuStandby::where(['id' => $goods_id])->find();

        if ($goods) {

            $Brand = BrandModel::where(['id' => $goods['brand_id']])->find();
            if (!$Brand) {
                return $this->error('logo不存在，请上传logo后再试！');
            }
            $logo_path = get_file_path($Brand['logo']);
            if (!($goods['main_img'] > 0)) {
                return $this->error('主图不存在，请上传后再试！');
            }

            $goods_main_image = get_file_path($goods['main_img']);
            $params = [
                "logo" =>  'http://host.docker.internal' . $logo_path,
                "goods" =>  'http://host.docker.internal' . $goods_main_image,
            ];

            if ($Brand['design_code'] == null) {

                $default_design_code =   module_config('yperp.default_design_code');

                if (!$default_design_code) {
                    return false;
                } else {
                    $Brand['design_code'] = $default_design_code;
                }
            }
            $sqlite_param = [
                "logo" =>  'http://erp.lhp' . $logo_path,
                "goods" =>  'http://erp.lhp' . $goods_main_image,
                'code' => $Brand['design_code'],
                'title' => $goods['itemNameAlias'] .  $goods['colourAlias'],

            ];
            $sqlite_param['buy_price_title'] = '';
            $sqlite_param['buy_price'] = '';
            $sqlite_param['height_price_title'] = '';
            $sqlite_param['height_price'] = '';

            if ($goods['sell_daily_price'] > 0) {
                $sqlite_param['buy_price_title'] = '虹创秒杀价：';
                $sqlite_param['buy_price'] = $goods['sell_daily_price'] . '元';
            } else {
                $sqlite_param['buy_price_title'] = '';
                $sqlite_param['buy_price'] = '';
            }

            if ($goods['sell_market_price']) {

                if ($sqlite_param['buy_price']) {
                    $sqlite_param['height_price_title'] = '某东价：';
                    $sqlite_param['height_price'] = $goods['sell_market_price'] . '元';
                } else {
                    $sqlite_param['buy_price_title'] = '虹创秒杀价：';
                    $sqlite_param['buy_price'] = $goods['sell_market_price'] . '元';
                }
            } else {
                $sqlite_param['height_price_title'] = '';
                $sqlite_param['height_price'] = '';
            }

            $this->get_db_sqlite($sqlite_param,);

            $save = env('root_path') . 'public' . DIRECTORY_SEPARATOR . 'goods.png';
            # 1.创建海报客户端对象
            $client = new Client("fastposter-token", "http://127.0.0.1:5001");
            # 3.生成海报并保存(提供图片流、二进制、base64等多种方式)
            $filename = $client->buildPoster($Brand['design_code'], $params)->save($save);

            // echo '<img src="' . DIRECTORY_SEPARATOR . 'goods.png" />';die;
            $res = $this->saveImage($filename);

            if ($res) {
                GoodsSkuStandby::where(['id' => $goods_id])->update(['main_img_alias' => $res['id']]);

                return $this->success('合并完成');;
            } else {

                return $this->error('上传失败');
            }
        } else {
            return $this->error('商品不存在');
        }
    }
    private function saveImage($imagePath)
    {
        $dir_name = date('Ymd');
        $file_dir = config('upload_path') . DIRECTORY_SEPARATOR . 'images/' . $dir_name . '/';
        if (!is_dir($file_dir)) {
            mkdir($file_dir, 0766, true);
        }
        pathinfo($imagePath, PATHINFO_FILENAME);
        $new_file = $file_dir . DIRECTORY_SEPARATOR . md5_file($imagePath) . '.' . pathinfo($imagePath, PATHINFO_EXTENSION);
        rename($imagePath, $new_file);

        //判断是fpm请求还是命令执行




        // 获取附件信息
        $file_info = [
            'uid' => (PHP_SAPI == 'cli') ? 1 : session('user_auth.uid'),
            'name' => pathinfo($new_file, PATHINFO_FILENAME),
            'mime' => mime_content_type($new_file),
            'path' =>  str_replace('\\', '/', str_replace(env('root_path') . 'public\\', '', $new_file)),
            'ext' => pathinfo($new_file, PATHINFO_EXTENSION),
            'size' => filesize($new_file),
            'md5' => md5_file($new_file),
            'sha1' => sha1_file($new_file),
            'thumb' => '',
            'module' => 'yperp',
            'width' => getimagesize($new_file)[0],
            'height' => getimagesize($new_file)[1],
        ];

        return AttachmentModel::create($file_info);
    }


    private function get_db_sqlite($data = [], $Sqlite_file = '')
    {
        if ($Sqlite_file == '') {
            $Sqlite_file = module_config('yperp.fastposter_sqlite_path');
            if (!$Sqlite_file) {
                return $this->error('fastposter设计器数据库地址未设置');
            }
        }
        $config = [
            // 数据库类型
            'type' => 'sqlite',
            // 数据库连接DSN配置
            'dsn' => 'sqlite:' . $Sqlite_file,
            // 数据库编码默认采用utf8
            'charset' => 'utf8',
        ];


        $Sqlite =   Db::connect($config)->table("posters")->where(['code' => $data['code']])->value('json');
        if (!$Sqlite) {
            return $this->error('设计ID不存在');
        }
        $SqliteDatas = json_decode($Sqlite, true);;
        foreach ($SqliteDatas['items'] as   &$value) {
            if (isset($data[$value['vd']])) {

                $value['v'] = $data[$value['vd']];
            }
        }

        Db::connect($config)->table("posters")->where(['code' => $data['code']])->update(['json' => json_encode($SqliteDatas, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)]);
        return json_decode($Sqlite, true);
    }
}
